<?php


namespace app\middleware;
use think\facade\Db;
use \Firebase\JWT\JWT;

class Usertoken
{
    public function handle($request, \Closure $next)
    {
        $token = trim($request->header('X-Token'));
        if (strpos($token, 'Bearer') === 0)
            $token = trim(substr($token, 6));
        if (!$token)
            return json(['status'=>0,'msg'=>'请登录后再操作']);

        try{
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, 'VliwSuvne', array('HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
                return json(['status'=>0,'msg'=>'认证失败']);
            }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
                return json(['status'=>0,'msg'=>'认证失败']);
            }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
                return json(['status'=>0,'msg'=>'认证失败']);
        }catch(Exception $e) {  //其他错误
                return json(['status'=>0,'msg'=>'认证失败']);
        }
        return $next($request);
    }
}
